<!-- 地址选择组件 AddressPicker.vue -->
<template>
    <view class="address-container">
        <!-- 当前选中城市 -->
        <view class="current-city" @click="showPicker = true">
            <text class="label">当前城市：</text>
            <text class="value">{{ selectedCity || '请选择城市' }}</text>
        </view>

        <!-- 城市选择弹窗 -->
        <uni-popup v-if="showPicker" type="bottom" @maskClick="showPicker = false">
            <view class="city-picker">
                <!-- 字母导航侧边栏 -->
                <scroll-view class="index-bar" scroll-y>
                    <view v-for="(letter, idx) in indexLetters" :key="idx" @click="scrollToLetter(letter)">
                        {{ letter }}
                    </view>
                </scroll-view>

                <!-- 按首字母分组列表 -->
                <scroll-view class="city-list" scroll-y :scroll-into-view="scrollIntoId" @scroll="handleScroll">
                    <view v-for="(group, key) in cityGroups" :key="key">
                        <view class="letter-title" :id="key">{{ key }}</view>
                        <view v-for="(item, index) in group" :key="index" class="city-item" @click="selectCity(item)">
                            {{ item.name }}
                        </view>
                    </view>
                </scroll-view>
            </view>
        </uni-popup>
    </view>
</template>
<script setup>
import { ref, computed } from 'vue';
import cityData from './city-data.json'; // 需自行准备城市数据‌:ml-citation{ref="4" data="citationList"}

// 响应式数据
const showPicker = ref(false);
const selectedCity = ref('');
const scrollIntoId = ref('');

// 转换城市数据为字母分组格式
const cityGroups = computed(() => {
    const grouped = {};
    cityData.forEach(city => {
        const letter = getFirstLetter(city.name);
        if (!grouped[letter]) grouped[letter] = [];
        grouped[letter].push(city);
    });
    return grouped;
});

// 生成字母索引列表
const indexLetters = computed(() => {
    return Object.keys(cityGroups.value).sort();
});

// 首字母提取方法（需自行实现或引入第三方库）
const getFirstLetter = (str) => {
    return str.charAt(0).toUpperCase();
};

// 滚动到指定字母区域
const scrollToLetter = (letter) => {
    scrollIntoId.value = letter;
};

// 选择城市
const selectCity = (city) => {
    selectedCity.value = city.name;
    showPicker.value = false;
};
</script>

<style>
/* 组件样式 */
.current-city {
    padding: 20rpx;
    background: #fff;
    border-bottom: 1rpx solid #eee;
}

.city-picker {
    height: 70vh;
    display: flex;
    background: #fff;
}

.index-bar {
    width: 60rpx;
    padding: 20rpx 0;
    background: #f5f5f5;
    text-align: center;
}

.city-list {
    flex: 1;
    padding-left: 30rpx;
}

.letter-title {
    padding: 20rpx 0;
    color: #666;
    background: #fff;
}

.city-item {
    padding: 24rpx 0;
    border-bottom: 1rpx solid #eee;
}
</style>